﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Core.Common;
using TTSClient.Models;

namespace TTSClient
{
    public partial class SettingForm : Form
    {
        private static readonly AppSetting appSetting = AppSetting.Current;
        internal ICollection<Language> Languages;
        public SettingForm()
        {
            InitializeComponent();
        }

        private void SettingForm_Load(object sender, EventArgs e)
        {
            txtApiHost.Text = appSetting.ApiUrl;
            txtAppId.Text = appSetting.AppId;
            txtApiKey.Text = appSetting.ApiKey;
            txtApiSecret.Text = appSetting.ApiSecret;
            txtRootPath.Text = appSetting.RootPath;
            if (Languages.IsNotNullOrEmpty())
            {
                cbVcn.DataSource = Languages;
                cbVcn.SelectedItem = Languages.FirstOrDefault(x => x.Code == appSetting.VcnCode);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            var value = txtAppId.Text.Trim();
            if (appSetting.AppId != value)
            {
                appSetting.AppId = value;
            }

            value = txtApiKey.Text.Trim();
            if (appSetting.ApiKey != value)
            {
                appSetting.ApiKey = value;
            }

            value = txtApiSecret.Text.Trim();
            if (appSetting.ApiSecret != value)
            {
                appSetting.ApiSecret = value;
            }

            value = cbVcn.SelectedValue.ToString();
            if (appSetting.VcnCode != value)
            {
                appSetting.VcnCode = value;
            }

            value = txtRootPath.Text.Trim();
            if (appSetting.RootPath != value)
            {
                appSetting.RootPath = value;
            }

            File.WriteAllText(Path.Combine(AppSettings.StartupPath, AppSettings.ConfigFileName), appSetting.ToJsonString());
            DialogResult = DialogResult.OK;
            Close();
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void BtnRootPath_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                txtRootPath.Text = folderBrowserDialog.SelectedPath;
            }
        }
    }
}
